package com.bit.lotterySystem.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.fasterxml.jackson.databind.type.LogicalType.Collection;

/**
 * @author wangw
 */
@Configuration
public class RedisUtil {
    private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    @Autowired
    private  StringRedisTemplate stringRedisTemplate;

    /**
     * 设置值
     * @param key
     * @param value
     * @return
     */
    public  boolean set(String key, String value) {
        try{
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            logger.error("Redis error, set({}, {})", key, value, e);
            return false;
        }
    }

    /**
     * 设置值（有过期时间）
     * @param key
     * @param value
     * @param time 分钟
     * @return
     */
    public  boolean set(String key, String value, Long time) {
        try{
            stringRedisTemplate.opsForValue().set(key,value,time, TimeUnit.MINUTES);
            return true;
        }catch (Exception e){
            logger.error("Redis error, set({}, {},{})", key, value,time, e);
            return false;
        }
    }

    /**
     * 获取值
     * @param key
     * @return
     */
    public String get(String key) {
        try{
            return StringUtils.hasText(key) ?
                    stringRedisTemplate.opsForValue().get(key):null;
        }catch (Exception e){
            logger.error("Redis error, get({})", key, e);
            return null;
        }
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        try{
            return StringUtils.hasText(key)?stringRedisTemplate.hasKey(key):false;
        }catch (Exception e) {
            logger.error("Redis error, hasKey({})", key, e);
            return false;
        }
    }

    /**
     * 删除值
     * @param keys
     * @return
     */
    public boolean del(String... keys) {
        try{
            if(keys != null && keys.length>0) {
                if(keys.length == 1) {
                    stringRedisTemplate.delete(keys[0]);
                }else{
                    stringRedisTemplate.delete((Collection<String>)CollectionUtils.arrayToList(keys));
                }
                return true;
            }
            return false;
        }catch (Exception e){
            logger.error("Redis error, del({})", keys, e);
            return false;
        }
    }

}
